//
// Created by 刘洋 on 2024/4/23.
//
#include "usartPacked.h"
#include "VOFA.h"
DATA data;
uint8_t rxBuffer;
void Data_Analysis(uint8_t cmd,uint8_t* data_ptr,uint8_t len)//鏁版嵁瑙ｆ瀽
{
    for(uint8_t i;i<len;i++)
    {
        data.data8[i] = *(data_ptr+i);
    }
    vofaTransmit(0, data.dataf);
}
//鎺ユ敹鏁版嵁
void Receive(uint8_t bytedata)
{
    static uint8_t step=0;//鐘舵?佸彉閲忓垵濮嬪寲涓?0 鍦ㄥ嚱鏁颁腑蹇呴』涓洪潤鎬佸彉閲?
    static uint8_t cnt=0,Buf[300],len,cmd,*data_ptr;
    static uint16_t crc16;
    //杩涜鏁版嵁瑙ｆ瀽 鐘舵?佹満
    switch(step)
    {
        case 0://鎺ユ敹甯уご1鐘舵??
            if(bytedata== 0xA5)
            {
                step++;
                cnt = 0;
                Buf[cnt++] = bytedata;
            }break;
        case 1://鎺ユ敹甯уご2鐘舵??
            if(bytedata== 0x5A)
            {
                step++;
                Buf[cnt++] = bytedata;
            }
            else if(bytedata== 0xA5)
            {
                step = 1;
            }
            else
            {
                step = 0;
            }
            break;
        case 2://鎺ユ敹鏁版嵁闀垮害瀛楄妭鐘舵??
            step++;
            Buf[cnt++] = bytedata;
            len = bytedata;
            break;
        case 3://鎺ユ敹鍛戒护瀛楄妭鐘舵??
            step++;
            Buf[cnt++] = bytedata;
            cmd = bytedata;
            data_ptr = &Buf[cnt];//璁板綍鏁版嵁鎸囬拡棣栧湴鍧?
            if(len == 0)step++;//鏁版嵁瀛楄妭闀垮害涓?0鍒欒烦杩囨暟鎹帴鏀剁姸鎬?
            break;
        case 4://鎺ユ敹len瀛楄妭鏁版嵁鐘舵??
            Buf[cnt++] = bytedata;
            if(data_ptr + len == &Buf[cnt])//鍒╃敤鎸囬拡鍦板潃鍋忕Щ鍒ゆ柇鏄惁鎺ユ敹瀹宭en浣嶆暟鎹?
            {
                step++;
            }
            break;
        case 5://鎺ユ敹甯у熬
            if(bytedata== 0xFF)//甯у熬鎺ユ敹姝ｇ‘
            {
                Data_Analysis(cmd,data_ptr,len);//鏁版嵁瑙ｆ瀽
                step = 0;
            }
            else if(bytedata == 0xA5)
            {
                step = 1;
            }
            else
            {
                step = 0;
            }
            break;
        default:step=0;break;//澶氫綑鐘舵?侊紝姝ｅ父鎯呭喌涓嬩笉鍙兘鍑虹幇
    }
}
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
    if(huart->Instance=USART2)
    {
        Receive(rxBuffer);
        HAL_UART_Receive_IT(&huart2,&rxBuffer,1);
    }
}